<?php 
	namespace Home\Controller;
	use Hdphp\Controller\Controller;
	use Home\Model\Users;
	class LoginController extends Controller{
		//用户模型类对象
		public $user;
		public function __init(){
			// 实例化模型对象
			$this->user=new Users;
		}
		public function index(){
			if(IS_POST){
				// 获取登录的用户名密码
				$username=q('post.username');
				$passwd=md5(q('post.passwd'));

				//调用验证规则
				if($this->user->create()){
					// 根据用户名查找用户信息
					$data=$this->user->where('username',$username)->find();
					// 判断用户密码是否对应
					if(isset($data)&&$data['passwd']==$passwd){
						//判断用户是否锁定
						if($data['statu']==1){
							View::error('账号已锁定，请联系管理员');
							die;
						}
						//压入session
						$_SESSION['userinfo']=array(
								'uid'=>$data['uid'],
								'nickname'=>$data['nickname'],
								'class'=>$data['class']
							);
						// 登录后更新登录的ip跟登录时间
						$this->user->afterLogin($data['uid']);
						View::success('登录成功',U('index/index'));
					}else{
						View::success('用户名或密码错误');
					}
				}else{
					View::error($this->user->getError());
				}
			}else{
				View::make();
			}
		}

		public function resetPwd(){
			if(IS_POST){
				$oldPwd=q('post.oldpasswd');
				$newPwd=q('post.passwd');
				$cPwd=q('post.confirmPwd');
				// p($_POST);
				if($newPwd==$cPwd){
					$data=Db::table('users')->where('uid',$_SESSION['userinfo']['uid'])->where('passwd',md5($oldPwd))->first();
					if($data){
						$res=Db::table('users')->where('uid',$_SESSION['userinfo']['uid'])->update(array('passwd'=>md5($newPwd)));
						go('logout');
					}else{
						View::error('原密码输入错误');
					}
				}else{
					View::error('两次密码输入不一致');
				}
			}
			View::make();
		}

		public function logout(){
			Session::del('userinfo');
			echo '<script>parent.location.href="index.php?c=login";</script>';
		}
	}
?>